package com.bwie.es.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.Shop;
import com.bwie.es.feign.EsFeifn;
import com.bwie.es.service.EsService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Author：作者姓名
 * @Package：com.bwie.es.service.impl
 * @Project：_yk
 * @name：EsServiceimpl
 * @Date：2024/6/17 12:59
 */
@Service
public class EsServiceimpl implements EsService {

    @Autowired
    private EsFeifn esFeifn;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public static final String INDEX_NAME="shop";

    @Override
    public List<Shop> List(Shop shop) {
        return null;
    }

    @Override
    public void Del() {
        try {
            DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
            deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery());
            restHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void Add(List<Shop> shops) {
        try {
            BulkRequest bulkRequest = new BulkRequest();
            shops.forEach(item->{
                bulkRequest.add(
                        new IndexRequest(INDEX_NAME)
                                .id(item.getId()+"")
                                .source(JSONObject.toJSONString(item), XContentType.JSON));});
            restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
